package com.lovo.project.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @title 文件上传
 * @author: luo
 * @date: 2020/11/6 9:58
 */
@WebServlet(name = "UploadFileServlet",value = "/uploadFile")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("file");
        String header = part.getHeader("content-disposition");
        //获得上传文件名
        String path = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
        // 获取文件的真实路径
//        String realPath = this.getServletContext().getRealPath("/upload");
        String newFileName = generateUploadFileName(getRealName(path));
        File file = new File("c:/upload");
        //文件夹不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }

        // 获取输入流
        InputStream inputStream = part.getInputStream();
        // 定义输出流
        FileOutputStream outputStream = new FileOutputStream(new File(file, newFileName));

        // 从输入流中读入数据并写到输出字节流中
        int len = -1;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }

        // 关闭资源
        outputStream.close();
        inputStream.close();

        // 删除临时文件
        part.delete();
        //向服务器返回新文件名
        response.getWriter().print(newFileName);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public static String getRealName(String path) {
        int index = path.lastIndexOf("\\");
        if (index == -1) {
            index = path.lastIndexOf("/");
        }
        return path.substring(index + 1);
    }
    //传入旧文件名，获得新的文件名
    public static String generateUploadFileName(String name){
        String suffixName = name.substring(name.lastIndexOf("."));
        return System.currentTimeMillis() + "_" +(int)(Math.random() * 100000) +suffixName;
    }

}
